//
//  TWDiscoverViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/9.
//  Copyright © 2017年 个人. All rights reserved.
//  发现页面

import UIKit
import SVProgressHUD

class TWDiscoverViewController: UIViewController {

    // MARK:- 懒加载
    fileprivate lazy var titleView : TWTitleView = TWTitleView()                                                             // 标题栏控件
    fileprivate lazy var hotVc : TWHotTableViewController = TWHotTableViewController()
    fileprivate lazy var classificationVc : TWClassificationViewController = TWClassificationViewController()
    fileprivate lazy var AuthorVc : TWAuthorTableViewController = TWAuthorTableViewController()
    fileprivate lazy var scrollView : UIScrollView = UIScrollView()                                                          // 用来存放所有子控制器的View
    fileprivate lazy var allCategoriesVc : TWAllCategoriesController = TWAllCategoriesController()
    fileprivate lazy var searchViewAnimator : TWSearchAnimator = TWSearchAnimator()
    
    // MARK:- 属性
    var titleArray : [TWDiscoverTitleModel] = [TWDiscoverTitleModel]()
    
    // MARK:- 系统回调函数
    override func viewWillAppear(_ animated: Bool) {
        // 在页面出现的时候就将黑线隐藏起来
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.backgroundColor = UIColor.white.withAlphaComponent(0.9)
    }
    override func viewWillDisappear(_ animated: Bool) {
        // 在页面消失的时候就让navigationbar还原样式
        navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        navigationController?.navigationBar.shadowImage = nil
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupNavigationBar()
        loadTitleData()
        initAllSubViewController()
        SVProgressHUD.show()
    }
}

// MARK:- UI界面
extension TWDiscoverViewController {
    fileprivate func setupStateBarBackground(){
        let barBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: BatteryHeight))
        barBackgroundView.backgroundColor = UIColor.white.withAlphaComponent(0.9)
        view.addSubview(barBackgroundView)
    }
    func setupNavigationBar(){
        let leftButton = UIButton(type: .custom)
        leftButton.setTitle("全部分类", for: .normal)
        leftButton.setTitleColor(UIColor.black, for: .normal)
        leftButton.titleLabel?.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 14)
        leftButton.addTarget(self, action: #selector(leftBarButtonItemDidClick), for: .touchUpInside)
        leftButton.sizeToFit()
        // 往导航栏左边添加一个间隙
        let leftItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        leftItem.width = -10
        navigationItem.leftBarButtonItems = [leftItem,UIBarButtonItem(customView: leftButton)]

        let titleLabel = UILabel()
        titleLabel.text = "Discover"
        titleLabel.font = UIFont(name: "Lobster 1.4", size: 30)
        titleLabel.textColor = UIColor.black
        titleLabel.sizeToFit()
        navigationItem.titleView = titleLabel
        
        let rightButton = UIButton(type: .custom)
        rightButton.setImage(UIImage(named: "bar_ic_search_44x44_"), for: .normal)
        rightButton.addTarget(self, action: #selector(rightBarButtonItemDidClick), for: .touchUpInside)
        rightButton.sizeToFit()
        // 往导航栏右边添加一个间隙
        let rightItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        rightItem.width = -15
        navigationItem.rightBarButtonItems = [rightItem,UIBarButtonItem(customView: rightButton)]
    }
    fileprivate func setupTitleView(titleArray : [TWDiscoverTitleModel]){
        titleView.frame = CGRect(x: 0, y: NavigationBarHeight, width: UIScreen.main.bounds.width, height: DiscovertitleViewHeight)
        titleView.titleArray = titleArray
        titleView.delegate = self as titleViewDelegate
        view.addSubview(titleView)
    }
    fileprivate func initAllSubViewController(){
        addChildViewController(hotVc)
        addChildViewController(classificationVc)
        addChildViewController(AuthorVc)
    }
    fileprivate func setupScrollView(){
        automaticallyAdjustsScrollViewInsets = false
        scrollView = UIScrollView(frame: view.bounds)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.scrollsToTop = false
        view.addSubview(scrollView)
        scrollView.contentSize = CGSize(width: CGFloat(titleArray.count) * TWScreenWidth, height: 0)
    }
    fileprivate func addChildVcWithIndex(){
        let index : Int = Int(scrollView.contentOffset.x / TWScreenWidth)
        let childView = childViewControllers[index].view
        let childVc = childViewControllers[index] as! TWRootViewController
        
        // 如果当前控制器已经被加过了，就不在继续计算frame和再次添加
        if ((childView?.window) != nil) {
            return
        }
        childVc.urlString = titleArray[index].apiUrl
        childView?.frame = scrollView.bounds
        scrollView.addSubview(childView!)
    }
}

// MARK:- 加载数据
extension TWDiscoverViewController {
     func loadTitleData(){
        TWNetworkTool.shareInstance.loadTitleViewData { (result, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载失败")
                return
            }
            guard let result = result else {
                return
            }
            for item in result {
                let titleModel = TWDiscoverTitleModel(dict: item)
                self.titleArray.append(titleModel)
            }
            SVProgressHUD.dismiss()
            self.setupScrollView()
            // 导航栏下方的分类视图
            self.setupTitleView(titleArray: self.titleArray)
            self.addChildVcWithIndex()
            self.setupStateBarBackground()
        }
    }
}

// MARK:- 监听点击
extension TWDiscoverViewController {
    @objc fileprivate func leftBarButtonItemDidClick(){
        present(allCategoriesVc, animated: true, completion: nil)
    }
    @objc fileprivate func rightBarButtonItemDidClick(){
        let searchVc : TWSearchViewController = TWSearchViewController()
        searchVc.modalPresentationStyle = .custom
        searchVc.transitioningDelegate = searchViewAnimator
        present(searchVc, animated: true, completion: nil)
    }
}


// MARK:- 代理方法
// MARK:- titleView的代理方法
extension TWDiscoverViewController : titleViewDelegate{
    func TitleViewTitleButtonDidClick(index: Int) {
        // 联动下面的scrollView,只需要左右滑动
        UIView.animate(withDuration: viewAnimationTime, animations: { 
            self.scrollView.contentOffset = CGPoint(x: CGFloat(index) * TWScreenWidth, y: self.scrollView.contentOffset.y)
        }) { (_) in
            self.addChildVcWithIndex()
        }
        // 设置index对应的tableView.scrollTotop为YES，其他为NO
        var i = 0
        for childVc in self.childViewControllers {
            if !childVc.isViewLoaded {
                // 如果这个控制器没有被创建，那就不处理（如果没有这句代码就会将所有的控制器全部创建出来）
                continue
            }
            let scrollView : UIScrollView = childVc.view as! UIScrollView
            // 如果不是scrollView（tableView也属于scrollView），就不处理
            if !scrollView.isKind(of: UIScrollView.self) {
                continue
            }
            // 按钮的索引与控制器对应上，才设置为yes，否则为No
            scrollView.scrollsToTop = (i == index) ? true : false
            i += 1
        }
        
    }
    func TitleViewPreviousClickTitleButton(index: Int) {
        print("第\(index)个按钮被重复点击")
    }
}


// MARK:- UIScrollViewDelegate的代理方法
extension TWDiscoverViewController : UIScrollViewDelegate{
    // 当用户松开scrollView，并且滑动结束（停止滚动）的时候
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index : Int = Int(scrollView.contentOffset.x / TWScreenWidth)
        titleView.titleButtonDidClick(button: titleView.subviews[index] as! TWTitleButton)
        addChildVcWithIndex()
    }
}




